package com.zy.design.demo.behavioral;

import java.util.ArrayList;
import java.util.List;

/**
 * 观察者模式
 * 特点：对象状态改变时，通知所有观察者。
 */
interface Observer {
    void update();
}

class Subject {
    private List<Observer> observers = new ArrayList<Observer>();

    public void attach(Observer o) { observers.add(o); }
    public void notifyObservers() {
        for (Observer o : observers) o.update();
    }
}

class ConcreteObserver1 implements Observer {
    public void update() { System.out.println("观察者1收到通知！"); }
}
class ConcreteObserver2 implements Observer {
    public void update() { System.out.println("观察者2收到通知！"); }
}

class Main2 {
    public static void main(String[] args) {
        Subject subject = new Subject();//主题
        Observer observer1 = new ConcreteObserver1();//观察者1
        subject.attach(observer1);//观察者订阅
        Observer observer2 = new ConcreteObserver2();//观察者2
        subject.attach(observer2);//观察者订阅
        subject.notifyObservers();//通知观察者
    }
}
